package com.ganbo.pattern.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by gan on 2020/6/9 21:36.
 */
public class JdkDynimicProxy implements InvocationHandler {

    private Object target;

    public JdkDynimicProxy(Object target) {
        this.target = target;
    }

    public Object getInstance(ClassLoader loader, Class<?>[] interfaces) {
        return Proxy.newProxyInstance(loader, interfaces, this);
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before================>");
        Object invoke = method.invoke(target, args);
        System.out.println("after================>");
        System.out.println("返回值==============>" + invoke);
        return invoke;
    }

    public static void main(String[] args) {
        ZhangShan zhangShan = new ZhangShan();
        JdkDynimicProxy proxy = new JdkDynimicProxy(zhangShan);
        Person p = (Person) proxy.getInstance(ZhangShan.class.getClassLoader(), ZhangShan.class.getInterfaces());
        System.out.println(p.hello());
    }
}


interface Person {
    String hello();
}

class ZhangShan implements Person {

    public String hello() {
        System.out.println("Hello world");
        return "这是返回值";
    }
}
